package com.toijng.weixintracker.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.widget.Toast;

import com.toijng.weixintracker.R;
import com.toijng.weixintracker.entity.Bag;
import com.toijng.weixintracker.entity.BagItem;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by lizhuo on 16/7/29.
 */
public class HongbaoClient {

    public static final String COMMITURL="http://localhost";

    private HongbaoApi  hongbaoApi;

    private static  HongbaoClient instance;

    private Retrofit retrofit;

    private SharedPreferences sharedPreferences;

    private Context mContext;


    private HongbaoClient(Context context)
    {
                 OkHttpClient client=new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(30, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .addInterceptor(createLoggerInterceptor()).build();

                mContext=context;

                retrofit=new Retrofit.Builder()
                .baseUrl(COMMITURL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

                sharedPreferences=mContext.getSharedPreferences("DATA",Context.MODE_PRIVATE);
                hongbaoApi=retrofit.create(HongbaoApi.class);

    }


    public static HongbaoClient getInstance(Context context) {
        if (instance == null) {
            synchronized (HongbaoClient.class) {
                if (instance == null) {
                    instance = new HongbaoClient(context);
                }
            }
        }
        return instance;
    }

    public void sendDetail(Bag bag)
    {

        String url=sharedPreferences.getString("URL","");

        if (!url.equals("")) {
            Call<Bag> bagCall = hongbaoApi.CommitBag(bag,url);

            bagCall.enqueue(new Callback<Bag>() {
                @Override
                public void onResponse(Call<Bag> call, Response<Bag> response) {

                }

                @Override
                public void onFailure(Call<Bag> call, Throwable t) {

                }
            });
        }else
        {
            Toast.makeText(mContext, mContext.getString(R.string.url_hint),
                    Toast.LENGTH_SHORT).show();
        }
    }

    private  LoggerInterceptor createLoggerInterceptor() {
        LoggerInterceptor httpLoggingInterceptor = new LoggerInterceptor("", true);
        httpLoggingInterceptor.setLevel(LoggerInterceptor.BOTH);
        return httpLoggingInterceptor;
    }
}
